import CONFIG from './lib/config'
import Rust from '@rmw/rust'
import dgram from 'dgram'

export default =>
  port = await CONFIG['udp/port'] =>
    udp = dgram.createSocket('udp4')
    udp.bind(0)
    new Promise (resolve)=>
      udp.on('listening', =>
        {port} = udp.address()
        udp.close()
        resolve port
      )

  Rust.upnp('rmw', port)

  udp = dgram.createSocket('udp4')
  new Promise (resolve,reject) =>
    udp.on 'error', (err)=>
      console.error(err)
      reject(err)
    udp.on 'listening', => resolve udp
    udp.bind port
    return

